package com.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * @Author 咕唧
 * @Date 2022/6/18 18:53
 * @Version 1.0
 */
@RestController
public class RedisController {
    //操作redis对象模板,默认使用jdk的方式保存数据
    private RedisTemplate redisTemplate;
    //操作string类型的redis对象模板
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/setobj")
    public String setObj(String key, String value) {
        //操作string类型的数据
        redisTemplate.opsForValue().set(key, value);
        return "success";
    }

    @PostMapping("/getobj")
    public Object getObj(String key) {
        //操作string类型的数据
        return redisTemplate.opsForValue().get(key);
    }

    @PostMapping("/set")
    public String set(String key, String value) {
        //操作string类型的数据
        stringRedisTemplate.opsForValue().set(key, value);
        return "success";
    }

    @PostMapping("/get")
    public String get(String key) {
        //操作string类型的数据
        return stringRedisTemplate.opsForValue().get(key);
    }

    @PostMapping("/pipel")
    public String testpipel(String key) {
        long start = System.currentTimeMillis();
        //开启一个管道
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                for (int i = 0; i < 10000; i++) {
                    //通过管道保存数据
                    connection.openPipeline();
                    connection.stringCommands().set(("spring boot" + i).getBytes(StandardCharsets.UTF_8), ("value" + i).getBytes(StandardCharsets.UTF_8));
                }
                connection.close();
                return null;
            }
        });
        long end = System.currentTimeMillis();
        System.err.println("时间:" + (end - start));
        return "success";
    }

}
